<!-- 用户管理 -->
<template>
  <div>
    <div flex>
      <div bd-fff mr-10px w="[25%]">
        <DeptTree v-model="queryParams.deptId" @node-click="handleQuery" />
      </div>
      <div overflow-hidden>
        <div h-75px bd-fff pt-30px pl-20px pr-20px mb-10px flex justify-between items-center>
          <div>
            <el-button
              v-hasPerm="['sys:user:add']"
              plain
              text-15px
              type="primary"
              style="
                font-size: 15px;
                color: #fff;
                background: linear-gradient(
                  90deg,
                  rgba(0, 108, 222, 1) 0%,
                  rgba(41, 182, 244, 1) 100%,
                  rgba(0, 163, 235, 1) 99%
                );
                border: none;
              "
              @click="handleOpenDialog()"
            >
              新增用户
            </el-button>
            <el-button
              v-hasPerm="'sys:user:delete'"
              type="danger"
              text-15px
              icon="delete"
              :disabled="selectIds.length === 0"
              @click="handleDelete()"
            >
              删除
            </el-button>
          </div>
          <div flex items-center flex-1 justify-end>
            <el-select
              v-model="queryParams.status"
              style="width: 100px; margin-right: 10px"
              placeholder="状态"
              clearable
            >
              <el-option label="正常" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
            <div mr--10px>
              <el-input
                v-model="queryParams.keywords"
                placeholder="用户名/昵称/手机号"
                @keyup.enter="handleQuery"
              ></el-input>
            </div>
            <el-button type="primary" text-15px z-2 icon="search" @click="handleQuery">
              搜索
            </el-button>
            <el-button
              plain
              text-15px
              icon="refreshRight"
              style="color: rgba(0, 108, 222, 1); border: 1px solid rgba(0, 108, 222, 1)"
              @click="handleResetQuery"
            >
              清空
            </el-button>
            <el-dropdown ml-10px trigger="click">
              <el-button
                plain
                text-15px
                icon="grid"
                style="color: rgba(0, 108, 222, 1); border: 1px solid rgba(0, 108, 222, 1)"
              >
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu style="color: #2778ff">
                  <el-dropdown-item icon="documentCopy" @click="dropdownItemClick('copy')">
                    复制
                  </el-dropdown-item>
                  <el-dropdown-item icon="printer" @click="dropdownItemClick('printer')">
                    打印
                  </el-dropdown-item>
                  <el-dropdown-item icon="expand" @click="dropdownItemClick('export')">
                    导出
                  </el-dropdown-item>
                  <el-dropdown-item icon="checked" @click="dropdownItemClick('archive')">
                    归档
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <div>
          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="pageData"
            :border="false"
            stripe
            :header-cell-style="{
              backgroundColor: '#F1F3F7',
              color: '#000',
            }"
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户名" prop="name" />
            <el-table-column label="昵称" width="150" align="center" prop="nickName" />
            <el-table-column label="性别" width="100" align="center">
              <template #default="scope">
                <DictLabel v-model="scope.row.gender" code="gender" />
              </template>
            </el-table-column>
            <el-table-column label="部门" align="center" width="150" prop="deptName" />
            <el-table-column label="手机号码" align="center" width="150" prop="phone" />
            <el-table-column label="状态" align="center" prop="status" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
                  {{ scope.row.status == 1 ? "正常" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="250" />
            <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button
                  v-hasPerm="'sys:user:password:reset'"
                  type="primary"
                  icon="RefreshLeft"
                  size="small"
                  link
                  @click="handleResetPassword(scope.row)"
                >
                  重置密码
                </el-button>
                <el-button
                  v-hasPerm="'sys:user:edit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row.id)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="'sys:user:delete'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            ref="paginationRef"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            background
            justify-center
            @pagination="handleQuery"
          />
        </div>
      </div>
    </div>
    <!-- 用户表单 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :show-close="false"
      :close-on-click-modal="false"
      width="900px"
      @close="handleCloseDialog"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="头像" prop="avatarUrl">
          <SingleImageUpload v-model:model-value="formData.avatarUrl" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" :readonly="!!formData.id" placeholder="请输入用户名" />
          <template #label="slotProps"></template>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            placeholder="请选择所属部门"
            :data="deptOptions"
            :props="{ children: 'children', label: 'name', value: 'id', disabled: '' }"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <Dict v-model="formData.gender" w="[100%]" code="gender" />
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            inline-prompt
            active-text="正常"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div pt-30px pb-40px flex justify-center>
          <el-button
            plain
            text-14px
            w-98px
            type="primary"
            style="
              font-size: 15px;
              color: #fff;
              background: linear-gradient(
                90deg,
                rgba(0, 108, 222, 1) 0%,
                rgba(41, 182, 244, 1) 100%,
                rgba(0, 163, 235, 1) 99%
              );
              border: none;
            "
            @click="handleSubmit"
          >
            提交
          </el-button>
          <el-button w-98px style="margin-left: 55px !important" plain @click="handleCloseDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入 -->
    <UserImport v-model="importDialogVisible" @import-success="handleQuery()" />
  </div>
</template>

<script setup lang="ts">
import { debounce } from "lodash-es";

import UserAPI, { UserForm, UserPageQuery, UserPageVO } from "@/api/system/user.api";
import DeptAPI from "@/api/system/dept.api";
import RoleAPI from "@/api/system/role.api";

import DeptTree from "./components/DeptTree.vue";
import UserImport from "./components/UserImport.vue";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const userFormRef = ref();

const dataTableRef = ref();
const paginationRef = ref();

const queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<UserPageVO[]>();
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增用户",
});

const formData = reactive<UserForm>({
  status: 1,
});

const rules = reactive({
  name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<OptionType[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
async function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.records;
      total.value = Number(data.total);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.pageNum = 1;
  queryParams.keywords = "";
  queryParams.status = undefined;
  queryParams.deptId = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 重置密码
function handleResetPassword(row: UserPageVO) {
  ElMessageBox.prompt("请输入用户【" + row.name + "】的新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showClose: false,
    confirmButtonClass: "message-box-confirm-button",
    cancelButtonClass: "message-box-cancel-button",
  }).then(
    ({ value }) => {
      if (!value || value.length < 6) {
        ElMessage.warning("密码至少需要6位字符，请重新输入");
        return false;
      }
      UserAPI.resetPassword(row.id, value).then(() => {
        ElMessage.success("密码重置成功，新密码是：" + value);
      });
    },
    () => {
      ElMessage.info("已取消重置密码");
    }
  );
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: string) {
  dialog.visible = true;
  // 加载角色下拉数据源
  roleOptions.value = await RoleAPI.getOptions();
  // 加载部门下拉数据源
  deptOptions.value = await DeptAPI.getOptions();

  if (id) {
    dialog.title = "修改用户";
    UserAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增用户";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        UserAPI.update(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.create(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "确认信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showClose: false,
    confirmButtonClass: "message-box-confirm-button",
    cancelButtonClass: "message-box-cancel-button",
  }).then(
    function () {
      loading.value = true;
      UserAPI.deleteByIds(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

// 导出用户
function handleExport() {
  UserAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

const dropdownItemClick = (type: string) => {
  console.log(type);
  if (type === "copy") {
    handleOpenImportDialog();
    console.log("复制");
  } else if (type === "printer") {
    console.log("打印");
  } else if (type === "export") {
    handleExport();
    console.log("导出");
  } else if (type === "archive") {
    console.log("归档");
  }
};

const setAdaptive = async () => {
  await nextTick();
  if (!dataTableRef.value) return;
  console.log(dataTableRef.value, "setAdaptive");
  const tableWrapper = dataTableRef.value.$el;
  let offsetBottom = 20;
  let paginationHeight = 0;

  // if (isPlainObject(props.adaptive)) {
  //   offsetBottom = props.adaptive.offsetBottom ?? offsetBottom;
  // }
  paginationHeight = paginationRef.value.$el.offsetHeight;

  tableWrapper.style.height = `${
    window.innerHeight - tableWrapper.getBoundingClientRect().top - offsetBottom - paginationHeight
  }px`;
};

const debounceSetAdaptive = debounce(setAdaptive, 60);

onMounted(() => {
  handleQuery();
  setAdaptive();
  window.addEventListener("resize", debounceSetAdaptive);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", debounceSetAdaptive);
});
</script>
